/**
 * axios请求方法封装
 */
import axios, { AxiosRequestConfig, AxiosResponse, Method } from 'axios'
import { ElMessage } from 'element-plus'
import { baseURL } from './env'
import { RefreshToken } from '@/service/common'
import router from '@/router'
import store from '@/store'


interface AxiosOption {
  url: string
  data?: any
  method?: Method
  loading?: boolean
  contentType?: string
}

interface ServiceResponse {
  success: boolean
  msg?: string
  code?: number
  data?: any
}
// 创建一个实例
const service = axios.create({
  baseURL: baseURL,
  timeout: 5000 // request timeout
})

export default async (option: AxiosOption): Promise<ServiceResponse> => {
  const { url, data = {}, method = 'GET', loading = true } = option

  const options: AxiosRequestConfig = {
    url: 'admin/' + url,
    baseURL,
    method,
    timeout: 30000,
    headers: {}
  }
  if (method === 'GET') {
    options.params = data
  } else {
    options.data = JSON.stringify(data)
    options.headers = {}
    options.headers["Content-Type"] = 'application/json;charset=utf-8'
  }
  store.commit('SET_LOADING', loading)
  const res = await axios(options)
  store.commit('SET_LOADING', false)
  if (res) {
    return res.data
  }
  return { success: false, data: {} }
}

axios.interceptors.request.use(
  (config: any) => {
    config.headers.Authorization = `Bearer ${localStorage.token}`
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

const errorType: { [key: number]: string } = {
  400: '请求错误',
  401: '未授权，请登录',
  403: '无权限访问',
  404: '请求地址出错',
  500: '系统错误，请联系管理员',
  503: '服务不可用'
}

axios.interceptors.response.use(
  (config: AxiosResponse) => {
    return config
  },
  (error) => {
    const response = error.response
    if (!response) {
      return ElMessage.error('无法连接服务器，请检查网络')
    }
    const code = response.status
    if (code === 417) {
      return ElMessage.error({
        message: response.data.msg
      })
    }
    if (code === 401) {
      return RefreshToken({ token: localStorage.refreshToken }).then((res: any) => {
        if (res.success) {
          localStorage.token = res.data.accessToken
          localStorage.refreshToken = res.data.refreshToken
          // 获取当前失败的请求
          const config = response.config
          //重置失败请求的配置
          config.headers = {}
          config.headers.Authorization = `Bearer ${localStorage.token}`
          return service(config)

        }
        else {
          //ElMessage.error(errorType[code])
          localStorage.refreshToken = ''
          localStorage.token = ''
          router.push('/login')
        }
      })
    }
    else ElMessage.error(errorType[code])
  }
)
